<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Session;

class ArticleController extends Controller
{
	//充值中心
    public function recharge( Request $request ){
        //接值
        $data = $request -> except('_token');
        $user_id = Session::get('user_id');//用户id
        //是否登录
        if(!$user_id){
            echo '<script>window.location.href="http://www.qian.com";</script>';
            die;
        }
        //是否成功充值
        if(empty($data['price'])){
            $price = '';
        }else{
            $price = floatval($data['price']);
        }
        //用户总金额
        $userInfo = DB::table('user')-> select('price')->where('id',$user_id)-> first();
        return view('article.recharge',[ "my_price"=> $userInfo,'price'=>$price]);
    }


    //充值记录
    public function recharge_record(){
        $user_id = Session::get('user_id');
        $userInfo = DB::table('chongzhi')
            ->select('notify_time','total_fee','subject')
            ->where('user_id',$user_id)
            ->orderBy('notify_time','desc')
            ->paginate(10);
        return view('article.record',[ "data"=> $userInfo ] );
    }

    //充值支付宝 支付页面
    public function recharge_do( Request $request ){
        $data = $request -> except('_token');
        $payMoney = $data['payMoney'];//支付金额
        $payMoney = 0.01;
        $user_id = Session::get('user_id');//用户id
        $order_id = time().$user_id.rand('11111','99999');//订单id
//        config('services.zhifubao');
        $alipay_config['partner']       = '2088401972679232';
        //收款支付宝账号
        $alipay_config['seller_email']  = '8@999.tv';
        //安全检验码，以数字和字母组成的32位字符
        $alipay_config['key']           = 'a2zh4gz93hbyskyegxn979rt1xdexblm';
        //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
        //签名方式 不需修改
        $alipay_config['sign_type']    = strtoupper('MD5');
        //字符编码格式 目前支持 gbk 或 utf-8
        //$alipay_config['input_charset']= strtolower('utf-8');
        //ca证书路径地址，用于curl中ssl校验
        //请保证cacert.pem文件在当前文件夹目录中
        $alipay_config['cacert']    = getcwd().'\\cacert.pem';
        //访问模式,根据自己的服务器是否支持ssl访问，若支持请选择https；若不支持请选择http
        $alipay_config['transport']    = 'http';


       $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => $alipay_config['partner'], // 合作身份者id
            "seller_email" => $alipay_config['seller_email'], // 收款支付宝账号
            "payment_type"  => '1', // 支付类型
            "notify_url"    => "http://www.qian.com/pay_notify_url", // 服务器异步通知页面路径
            "return_url"    => "http://www.qian.com/pay_return_url", // 页面跳转同步通知页面路径
            "out_trade_no"  => $order_id, // 商户网站订单系统中唯一订单号
            "subject"   => '蜘蛛币余额充值'.$payMoney, // 订单名称
            "total_fee" => $payMoney, // 付款金额
            "body"  => $user_id, // 用户id
            "show_url"  => "", // 商品展示地址 可选
            "anti_phishing_key" => "", // 防钓鱼时间戳  若要使用请调用类文件submit中的query_timestamp函数
            "exter_invoke_ip"   => "", // 客户端的IP地址
            "_input_charset"    => 'utf-8', // 字符编码格式
        );
        // 去除值为空的参数
        foreach ($parameter as $k => $v) {
            if (empty($v)) {
                unset($parameter[$k]);
            }
        }
        // 参数排序
        ksort($parameter);
        reset($parameter);

        // 拼接获得sign
        $str = "";
        foreach ($parameter as $k => $v){
            if (empty($str)) {
                $str .= $k . "=" . $v;
            } else {
                $str .= "&" . $k . "=" . $v;
            }
        }
        $parameter['sign'] = md5($str . $alipay_config['key']);
        $parameter['sign_type'] = $alipay_config['sign_type'];


       $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='https://mapi.alipay.com/gateway.do?_input_charset=utf-8' method='get'>";
        foreach ($parameter as $k => $v) {
            $sHtml.= "<input type='hidden' name='" . $k . "' value='" . $v . "'/>";
        }

        $sHtml = $sHtml."<script>document.forms['alipaysubmit'].submit();</script>";

        echo $sHtml;
    }


    //支付宝同步通知
    public function return_url( Request $request ){
        $data = $request -> except('_token');
        if($data['is_success'] == 'T'){
            $order['user_id'] = $data['body'];//用户user_id
            $order['buyer_email'] = $data['buyer_email'];//用户email
            $order['buyer_id'] = $data['buyer_id'];//支付宝用户id
            $order['notify_id'] = $data['notify_id'];//支付用户id
            $order['notify_time'] = $data['notify_time'];//异步时间
            $order['out_trade_no'] = $data['out_trade_no'];//商户网站订单系统中唯一订单号
            $order['seller_email'] = $data['seller_email'];//商户网站订单系统中唯一订单号
            $order['subject'] = $data['subject'];//订单名称
            $order['total_fee'] = $data['total_fee'];//付款金额
            $order['trade_no'] = $data['trade_no'];//支付宝订单号
            $order['trade_status'] = $data['trade_status'];//支付宝订单号

            //入充值日志表
            $ree = DB::table('user')->where('id',$order['user_id'])->first();
            $arr['u_id'] = $data['body'];
            $arr['desc'] = "用户".$ree->name."在".date('Y-m-d H:i:s',time())."使用支付宝在蜘蛛网充值蜘蛛币".$data['total_fee']."元";
            $insert_log = DB::table('log_price')-> insert($arr);

            //充值
            $insert_id = DB::table('chongzhi')
                -> insertGetId($order);
            if($insert_id){
                $res = DB::table('user')->where('id',$order['user_id'])->increment("price",$order['total_fee']);
                if($res){
                    //跳入页面
                    echo '<script>location.href="http://www.qian.com/recharge?price='.$data['total_fee'].'";</script>';
                }else{
                    echo 'error!';
                }
            }else{
                echo 'error';
            }
        }
    }

    //支付宝异步通知
    public function notify_url( Request $request ){
        $data = $request -> except('_token');
        $order['user_id'] = $data['body'];//用户user_id
        $order['buyer_email'] = $data['buyer_email'];//用户email
        $order['buyer_id'] = $data['buyer_id'];//支付宝用户id
        $order['notify_id'] = $data['notify_id'];//支付用户id
        $order['notify_time'] = $data['notify_time'];//异步时间
        $order['out_trade_no'] = $data['notify_time'];//商户网站订单系统中唯一订单号
        $order['seller_email'] = $data['seller_email'];//商户网站订单系统中唯一订单号
        $order['subject'] = $data['subject'];//订单名称
        $order['total_fee'] = $data['total_fee'];//付款金额
        $order['trade_no'] = $data['trade_no'];//支付宝订单号
        $order['trade_status'] = $data['trade_status'];//支付宝订单号

        //入充值日志表
        $ree = DB::table('user')->where('id',$order['user_id'])->first();
        $arr['u_id'] = $data['body'];
        $arr['desc'] = "用户".$ree->name."在".date('Y-m-d H:i:s',time())."在蜘蛛网充值蜘蛛币".$data['total_fee']."元";
        $insert_log = DB::table('log_price')-> insert($arr);

        //充值
        $insert_id = DB::table('chongzhi')
            -> insertGetId($order);
        if($insert_id){
            $res = DB::table('user')->where('id',$order['user_id'])->increment("price",$order['total_fee']);
            if($res){
                echo 'success!';
            }else{
                echo 'error!';
            }
        }else{
            echo 'error';
        }
    }
	
	// 执行 上传 主队图标
	public function doTeamPicture( $for=1 )
	{
		// 日期 作为新建目录名
		$time = date('Ymd');
		// 线上 目标目录 
		$dir= "../../image/images/recommend/".$time;
		// 检测 文件 或者 目录 是否存在
		if( !file_exists($dir) )
		{	
			// 创建 目录
			mkdir( $dir,0777,true );
		}
		$filename = '';
		foreach( $_FILES as $key => $file_info )
		{
			// 文件名
			$fileName = $file_info['name'];
			// 通过文件名 后缀
			$ext = pathinfo( $fileName,PATHINFO_EXTENSION );
			if( !in_array($ext,array('jpg','jpeg','png','gif') )  )
			{
				echo  "<script>window.parent.showerror('请上传正确格式的图片')</script>";
				return ;
			}
			
			if( $file_info['size'] > 2097152 )
			{
				echo  "<script>window.parent.showerror('请上传小于2M的图片')</script>";
				return ;
			}
			
			$image_info=getimagesize($file_info['tmp_name']);
			if( $image_info[0]>800 || $image_info[1]>500 ){
				echo  "<script>window.parent.showerror('请上传尺寸小于800*500的图片')</script>";
				return ;
			}
			
			
			// 临时目录
			$srcDir = $file_info['tmp_name'];
			// 新的 文件名
			$newName = rand(1,1000000).".".$ext;
			// 移动成功
			$res = move_uploaded_file( $srcDir, $dir."/".$newName );
			$filename="/images/recommend/".$time."/".$newName;
			if( $res )
			{
				// 线上
				$file = str_replace("/images",config('app.imgPath')."/images",$filename);
				// 返回 显示 图片
				if( $for==1 )
				{
					echo  "<script>window.parent.showPic('".$file."','img_home_pic','".$filename."')</script>";
				}else
				{
					echo  "<script>window.parent.showPic('".$file."','img_away_pic','".$filename."')</script>";
				}
				
				return ;
			}else
			{
				echo  "<script>window.parent.showerror('上传失败')</script>";
				return ;
			}
			break;
		}
		
	}

	
	// 赛事推荐
	public function recommendGame()
	{
		if( !Session::get('user_id') )
		{
			return redirect('/');
		}
		// 赛事推荐
		return view('article.recommend');
	}
	
	
	// 执行创建 赛事推荐
	public function dorecommend( Request $request )
	{
		if( !Session::get('user_id') )
		{
			$this->show_msg('请先登录,才能发表赛事推荐');
		}
		
		// 接收数据
		$data = $request -> only('home','home_pic','away','away_pic','match_date','home_index','p_index','away_index','checkbox','content','status');
		// 转换日期格式
		$data['match_date'] = date( 'Y-m-d H:i:s',strtotime($data['match_date']) );
		$home_length = mb_strlen( $data['home'],'utf-8' );
		
		if( $home_length<1 )
		{
			$this->show_msg('请输入主队队名');
		}
		
		if( empty($data['home_index']) )
		{
			$this->show_msg('请输入主队指数');
		}
		
		if( empty($data['home_pic']) )
		{
			$this->show_msg('请上传主队图片');
		}
		
		
		$away_length = mb_strlen( $data['away'],'utf-8' );
		if( $away_length<1 )
		{
			$this->show_msg('请输入客队队名');
		}
		
		if( empty($data['away_index']) )
		{
			$this->show_msg('请输入客队指数');
		}
		
		if( empty($data['away_pic']) )
		{
			$this->show_msg('请上传客队图片');
		}
		
		if( empty($data['match_date']) )
		{
			$this->show_msg('请选择比赛日期');
		}
		
		
		if( empty($data['p_index']) )
		{
			$this->show_msg('请输入平指数');
		}
		
		if( empty($data['content']) )
		{
			$this->show_msg( '请输入赛事推荐内容' );
		}
		
		if( empty($data['checkbox']) )
		{
			$this->show_msg('请选择推荐类型');
		}
		
		// 检查百度编辑器里的配置图片显示地址 与 app.imgPath 是否一致 必须一致
		// 线上
		$data['content'] = str_replace( config('app.imgPath'),'',$data['content'] );
		// 正则 匹配图片地址
		$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
		preg_match_all($pattern,$data['content'],$pics);
		// 获取用户是否上传了图片
		$pics=$pics[1];
		
		// 创建
		$data['create_at'] = date('Y-m-d H:i:s',time());
		$data['user_id'] = Session::get('user_id');
		
		// 1. 主表
		$insert_id = DB::table('new_recommend')->insertGetId( $data );
		if( !$insert_id )
		{
			$this->show_msg( '发表失败' );
		}
		
		
		// 用户 内容里 上传了图片
		if( count($pics) > 0 )
		{
			// 遍历 图片 地址信息
			foreach( $pics as $key => $file_path )
			{
				$pic = array();
				if( $key==0 )
				{
					// 封面
					$pic['status'] = 1;
				}
				$pic['new_recommend_id'] = $insert_id;
				$pic['pic_url'] = $file_path;
				// 3. 图片表
				DB::table('new_recommend_pic')->insertGetId($pic);
			}
		}
		
		if( $data['status']=='1' )
		{
			$this->show_msg( '已存入草稿箱' );
		}else
		{
			$this->show_msg( '发表成功,审核通过后即可显示' );
		}
		
	
	}
	
	
	// 用户 发表文章 页面
	public function new_article( $article_id='' )
	{
		if( empty(Session::get('user_id')) )
		{
			// 请先 登录
			return redirect('/');
		}
		
		// 获取 文章 分类
		$category = DB::table('category')
				// 所属球吧的分类
				-> where('pid','=',15)
				-> get();
		
		
		if( $article_id == '' )
		{
			// 创建
			return view( 'article.add',[ 'title'=>'发表文章','category'=>$category ] );
		}else
		{
			// 编辑
			$article_info = DB::table('article')
								-> where('id', $article_id)
								-> first();
			// 没有这篇文章
			if( empty($article_info) )
			{
				return redirect('/');
			}
			// 没有编辑这篇文章的权限
			if( $article_info->user_id != Session::get('user_id') )
			{
				return redirect('/');
			}
			// dd($article_info);
			
			// 线上
			$article_info->content = str_replace( '/images',config('app.imgPath').'/images',$article_info->content );
			return view( 'article.add',[ 'title'=>'编辑文章','article_info'=>$article_info,'category'=>$category  ] );
		}
		
	}
	
	
	// 个人中心页
	public function personCenter()
	{
		if( empty(Session::get('user_id')) )
		{
			// 请先登录
			return redirect('/');
		}
		$user_info = DB::table('user')
				-> where( 'id','=',Session::get('user_id') )
				-> first();
		// 线上
		$user_info->pic_url = str_replace( '/images',config('app.imgPath').'/images',$user_info->pic_url );		
				
		return view( 'article.person',[ 'user_info'=>$user_info ] );
		
	}
	
	
	// 稿件管理
	public function manage()
	{
		if( empty(Session::get('user_id')) )
		{
			// 请先登录
			return redirect('/');
		}
		// 个人 中心 文章列表
		$person_articles = DB::table('article as a')
					-> select('a.id','a.title',DB::raw("case when a.status=1 then '草稿' when a.status=2 then '待审核' when a.status=3 then '审核通过' when a.status=4 then '已推荐' when a.status=5 then '头条' when a.status=6 then '审核不通过' end as statusInfo"),'a.status','a.create_at')
					-> where( 'a.user_id','=',Session::get('user_id') )
					-> orderBy('a.create_at','desc')
					-> paginate(10);
		$articles = array();
		foreach( $person_articles as $key => $article_info )
		{
			// 找 封面
			$pic = DB::table('article_pic')
					-> where( 'article_id','=',$article_info->id )
					-> where( 'status','=',1 )
					-> first();
			if( empty($pic) )
			{
				$articles[$key]['pic_url'] = config('app.imgPath').'/images/moren.jpg';
			}else
			{
				// 线上
				$articles[$key]['pic_url'] = str_replace( '/images',config('app.imgPath').'/images',$pic->pic_url );
			}
			// 评论 总数
			$articles[$key]['commont_total'] = DB::table('comments')
					-> where( 'record_id','=',$article_info->id )
					-> where( 'type','=',2 )
					-> count();
			$articles[$key]['id'] = $article_info->id;
			$articles[$key]['title'] = $article_info->title;
			$articles[$key]['status'] = $article_info->status;
			$articles[$key]['statusInfo'] = $article_info->statusInfo;
			$articles[$key]['create_at'] = $article_info->create_at;
			
		}
		
		return view( 'article.article',[ 'articles'=>$articles,'person_articles'=>$person_articles ] );
		
	}
	
	
	// 个人中心 我的收藏
	public function myCollect()
	{
		if( !Session::get('user_id') )
		{
			return redirect('/');
		}
		$all_collects = DB::table('collect')
			-> where('user_id','=',Session::get('user_id'))
			-> orderBy('create_at','desc')
			-> paginate(10);
		$new_collect = array();
		foreach( $all_collects as $key => $collect )
		{
			$type = $collect -> type;
			switch( $type )
			{
				case '1':
					// 1.资讯
					$news = DB::table('news as n')
						-> select('n.id','n.title','np.pic_url','n.create_at')
						-> leftJoin('news_pic as np','np.news_id','=','n.id')
						-> where('n.id','=',$collect->record_id)
						-> where( 'np.status','=',1 )
						-> first();
					if( !empty($news) )
					{
						// 评论总数
						$comments_total = DB::table('comments')
									-> where('record_id','=',$news->id)
									// 资讯
									-> where('type','=',1)
									-> count();
						$new_collect[$key]['comments_total']=$comments_total;
						$new_collect[$key]['id']=$news->id;
						$new_collect[$key]['type']=1;
						$new_collect[$key]['title']=$news->title;
						$new_collect[$key]['create_at']=$news->create_at;
						$new_collect[$key]['collect_id']=$collect->id;
						// 线上
						$new_collect[$key]['pic_url'] = str_replace( '/images',config('app.imgPath').'/images',$news->pic_url );
					}
				break;
				case '2':
					// 2.文章
					$article = DB::table('article')
						-> where('id','=',$collect->record_id)
						-> first();
					if( !empty($article) )
					{
						$pic = DB::table('article_pic')
								-> select('pic_url')
								-> where( 'article_id','=',$article->id )
								// 找 封面
								-> where( 'status','=',1 )
								-> first();
						if( empty($pic) )
						{
							$new_collect[$key]['pic_url'] = config('app.imgPath').'/images/moren.jpg';
						}else
						{
							// 线上
							$new_collect[$key]['pic_url'] = str_replace( '/images',config('app.imgPath').'/images',$pic->pic_url );
						}
						
						// 评论总数
						$comments_total = DB::table('comments')
									-> where('record_id','=',$article->id)
									// 文章
									-> where('type','=',2)
									-> count();
						$new_collect[$key]['comments_total']=$comments_total;
						$new_collect[$key]['id']=$article->id;
						$new_collect[$key]['type']=2;
						$new_collect[$key]['title']=$article->title;
						$new_collect[$key]['create_at']=$article->create_at;
						$new_collect[$key]['collect_id']=$collect->id;
					}
				break;
				case '3':
					// 3.图库
					$photos = DB::table('photos as p')
							-> select('p.id','p.title','pp.pic_url','p.create_at')
							-> leftJoin('photos_pic as pp','pp.photo_id','=','p.id')
							-> where('p.id','=',$collect->record_id)
							// 封面
							-> where( 'pp.status','=',1 )
							-> first();
					if( !empty($photos) )
					{	
						// 评论总数
						$comments_total = DB::table('comments')
									-> where('record_id','=',$photos->id)
									// 图库
									-> where('type','=',3)
									-> count();
						$new_collect[$key]['comments_total']=$comments_total;
						$new_collect[$key]['id']=$photos->id;
						$new_collect[$key]['type']=3;
						$new_collect[$key]['title']=$photos->title;
						$new_collect[$key]['create_at']=$photos->create_at;
						// 线上
						$new_collect[$key]['pic_url'] = str_replace( '/images',config('app.imgPath').'/images',$photos->pic_url );
						$new_collect[$key]['collect_id']=$collect->id;
					}
				break;
			
			}
		}
		return view('article.collect',['collect'=>$new_collect,'all_collects'=>$all_collects]);
	
	}
	
	
	
	// 执行 创建 编辑 文章
	public function createArticle( $article_id='', Request $request )
	{
		if( !Session::get('user_id') )
		{
			$this->show_msg('请先登录，才能发表文章');
		}
		
		// 增加分类选择
		$data = $request -> only('title','content','keywords','desc','from','status','category_id' );
		
		
		if( empty($data['category_id']) )
		{
			$this->show_msg('请选择您的文章分类');
		}
		
		if( !in_array($data['category_id'],array(16,17,18)) )
		{
			$this->show_msg('选择分类有误');
		}
		
		
		$title_length=mb_strlen( $data['title'],'utf-8' );
		
		if( $title_length<1 )
		{
			$this->show_msg('请输入标题');
		}
		if( $title_length>50 )
		{
			$this->show_msg('标题输入过长');
		}
		
		if( empty($data['keywords']) )
		{
			$data['keywords']='';
		}
		if( empty($data['desc']) )
		{
			$data['desc']='';
		}
		if( empty($data['from']) )
		{
			$data['from']='';
		}
		
		if( empty($data['content']) )
		{
			$this->show_msg( '请输入文章内容' );
		}
		
		// 检查百度编辑器里的配置图片显示地址 与 app.imgPath 是否一致 必须一致
		// 线上
		$data['content'] = str_replace( config('app.imgPath'),'',$data['content'] );
		// 正则 匹配图片地址
		$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg]))[\'|\"].*?[\/]?>/";
		preg_match_all($pattern,$data['content'],$pics);
		$pics=$pics[1];
		
		if( $article_id == '' )
		{
			// 创建
			$data['create_at'] = date('Y-m-d H:i:s',time());
			$data['user_id'] = Session::get('user_id');
			
			// 1. 主表
			$insert_id = DB::table('article')->insertGetId( $data );
			if( !$insert_id )
			{
				$this->show_msg( '发表失败' );
			}
			// 用户 内容里 上传了图片
			if( count($pics) > 0 )
			{
				// 遍历 图片 地址信息
				foreach( $pics as $key => $file_path )
				{
					$pic = array();
					if( $key==0 )
					{
						// 封面
						$pic['status'] = 1;
					}
					$pic['article_id'] = $insert_id;
					$pic['pic_url'] = $file_path;
					// 3. 图片表
					DB::table('article_pic')->insertGetId($pic);
				}
			}
			
			if( $data['status']=='1' )
			{
				$this->show_msg( '已存入草稿箱' );
			}else
			{
				$this->show_msg( '发表成功,审核通过后即可显示' );
			}
			
			
			
		}else
		{
			// 编辑
			$user_id = DB::table('article')
							-> select('user_id')
							-> where( 'id','=',$article_id )
							-> first();
			if( $user_id->user_id != Session::get('user_id') )
			{
				$this -> show_msg('您无权修改此篇文章');
			}
			// 获取 现有旧表的 图片地址
			$old_pics = DB::table('article_pic')
							-> where( 'article_id','=',$article_id )
							-> get();
			$old = array();
			// 里面如果 有图片的话
			foreach( $old_pics as $key => $pic_info )
			{
				// 转成数组
				$old[ $pic_info->id ]=$pic_info->pic_url;
			}
			
			// 获取差集 结果为要删除的图片
			$del = array_diff($old,$pics);
			
			if( count($del)>0 )
			{
				foreach( $del as $pic_id => $pic_info )
				{
					// 线上
					$file = "../../image".$pic_info;
					
					if( file_exists($file) )
					{
						// 删除 文件
						unlink( $file );	
					}
					// 删除 图片表旧数据
					$delete = DB::table('article_pic')
								-> where( 'id','=',$pic_id )
								-> delete();
					
				}
			}
			
			// 获取差集 为新增图片
			$new = array_diff( $pics,$old );
			
			foreach( $new as $key => $file_path )
			{
				$pic = array();
				if( $key==0 )
				{
					// 封面
					$pic['status'] = 1;
				}
				$pic['article_id'] = $article_id;
				$pic['pic_url'] = $file_path;
				// 2. 图片表
				DB::table('article_pic')->insertGetId($pic);
				
			}
			// 3. 主表数据
			$upd_res = DB::table('article')
							-> where( 'id','=',$article_id )
							-> update( $data );
			if( !$upd_res )
			{
				$this -> show_msg( '文章编辑失败' );
				
			}
			if( $data['status']=='1' )
			{
				$this->show_msg( '已存入草稿箱' );
			}else
			{
				$this -> show_msg( '文章编辑成功,审核通过后即可显示' );
			}
			
		
		}
	
	}
	
	
	// 获取 球吧 推荐专区
	public function getRecommend()
	{
		// 推荐
		$tuijian = DB::table('article as a')
				-> select('a.id','a.title','ap.pic_url','c.name as cate_info','c.id as cid')
				-> leftJoin('article_pic as ap','ap.article_id','=','a.id')
				-> leftJoin('category as c','c.id','=','a.category_id')
				// 1草稿 2待审核 3审核通过 4推荐 5头条 6未通过
				-> where( 'a.status','=','4' )
				// 封面
				-> where( 'ap.status','=',1 )
				-> take(10)
				-> get();
		$recommend = array();
		foreach( $tuijian as $key => $info  )
		{
			
			$recommend[$key]['id'] = $info->id;
			$recommend[$key]['title'] = $info->title;
			$recommend[$key]['cate_info'] = $info->cate_info;
			$recommend[$key]['cid'] = $info->cid;
			// 线上 图片 地址 
			$str = str_replace("/images",config('app.imgPath')."/images",$info->pic_url);
			$recommend[$key]['pic_url'] = $str;
		}

		return $recommend;
	}
	
	
	
	// 球吧 列表
	public function clubList( $category_id='',Request $request)
	{
		
		// 获取搜索内容
		$keyTitle = $request -> input('keyTitle',"");
		if( empty($keyTitle) ){
			// 为空 说明没有搜索
			$one = 'a.id';
			$two = '!=';
			$three = '0';
			if( Session::get('commonSearch') )
			{
				Session::forget('commonSearch');
			}
			if( Session::get('commonSelect') )
			{
				Session::forget('commonSelect');
				// 选中的文章类型
				Session::put('commonSelect',2);
			}
		}else
		{
			// 是文章名
			$one = 'a.title';
			$two = 'like';
			$three = '%'.$keyTitle.'%';
			Session::put('commonSearch',$keyTitle);
			if( Session::get('commonSelect') )
			{
				Session::forget('commonSelect');
				// 选中的文章类型
				Session::put('commonSelect',2);
			}
			
		}
		
		
		if( $category_id=='' )
		{
			// 全部
			$four = "!=";
			$five = "";
		}else
		{
			// 指定某个分类
			$four = "=";
			$five = $category_id;
			
		}
		
		// 16预测 17情报 18杂谈
		$allow = array( 16,17,18 );
		// 不在 查看范围内 默认全部
		if( !in_array($category_id,$allow) )
		{
			$four = "!=";
			$five = "";
		}
		
		// 获取 文章
		$all_articles = DB::table('article as a')
				-> select( 'a.id','a.title','a.from','a.good','a.create_at',"u.name as username",DB::raw("case when a.category_id=16 then '预测' when a.category_id=17 then '情报' when a.category_id=18 then '杂谈' end as cate_info"),DB::raw("replace(u.pic_url,'/images','".config('app.imgPath')."/images' ) as pic_url "  ),'a.user_id' )
				-> leftJoin('user as u','u.id','=','a.user_id' )
				-> leftJoin('category as c','c.id','=','a.category_id')
				// 3审核通过 4推荐 5头条
				-> whereIn( 'a.status',array(3,4,5) )
				-> where( $one,$two,$three ) 
				-> where( 'c.id',$four,$five )
				// 按 发布 时间 排序
				-> orderBy('a.create_at','desc')
				-> paginate(10);
		
		// 文章 总数
		$articles_count = DB::table('article as a')
				-> select( 'a.id' )
				-> leftJoin('category as c','c.id','=','a.category_id')
				// 3审核通过 4推荐 5头条
				-> whereIn( 'a.status',array(3,4,5) )
				-> where( $one,$two,$three ) 
				-> where( 'c.id',$four,$five )
				-> count();
		
		$page_articles = array();
		foreach( $all_articles as $key => $article_info )
		{
			$articles = array();
			$articles['id']= $article_info->id;
			$articles['title']= $article_info->title;
			$articles['from']= $article_info->from;
			$articles['good']= $article_info->good;
			$articles['create_at']= $article_info->create_at;
			$articles['username']= $article_info->username;
			$articles['user_id']= $article_info->user_id;
			$articles['cate_info']= $article_info->cate_info;
			// 评论 计数
			$articles['comments_total'] = DB::table('comments')
							// 
							-> where( 'record_id','=',$article_info->id )
							// 文章 类型
							-> where( 'type','=',2 )		
							-> count();
			// $pic = DB::table('article_pic as ap')
							// -> select('ap.pic_url')
							// -> where('ap.article_id','=',$article_info->id)
							// 封面
							// -> where( 'ap.status','=',1 )
							// -> first();
			// if( empty($pic) )
			// {
				// $str = "/images/moren.jpg";
			// }else
			// {
				// $str = $pic -> pic_url;
			// }
			// 线上 图片 地址 
			// $str = str_replace("/images",config('app.imgPath')."/images",$str);
			// $articles['pic_url']= $str;
			$articles['pic_url']= $article_info->pic_url;
			$page_articles[$key] = $articles;
		}
		// dd($page_articles);
		// 获取 推荐专区
		$recommend = $this -> getRecommend();
		
		
		if( $category_id )
		{
			$tdk = DB::table('category as c') 
					-> where( 'c.id','=',$category_id )
					-> first();
		}else
		{
			// 球吧
			$tdk = DB::table('category as c') 
					-> where( 'c.id','=',15 )
					-> first();
		}

        // 资讯列表页 配置
        $webConfig = DB::table('webconfig')
            -> select('webName')
            -> where('id',1)
            -> first();
		
		// 球吧 列表
		return view( 'article.clubList',['webConfig'=>$webConfig, 'recommend'=>$recommend,'page_articles'=>$page_articles,'all_articles'=>$all_articles,'keyTitle'=>$keyTitle,'category_id'=>$category_id,'articles_count'=>$articles_count,'tdk'=>$tdk ] );
	
	}
	
	
	// 球吧 文章 详情 页
	public function articleDetail( $article_id, Request $request )
	{
		// 单条 详情
		$article = DB::table('article as a')
					-> select('a.*','u.name','u.id as uid')
					-> where( 'a.id','=',$article_id )
					-> leftJoin( 'user as u','u.id','=','a.user_id' )
					// 1草稿 2待审核 3审核通过 4推荐 5头条 6未通过
					-> whereIn( 'a.status',array(3,4,5) )
					-> first();
		if( empty($article) )
		{
			return view('errors.404');
		}
		
		
		// 线上 图片 地址 
		$str = str_replace("/images",config('app.imgPath')."/images",$article->content);
		
		
		// 获取 全部 球员
		$allPlayer = DB::table('player_info')
					-> select('name','player_id')
					-> get();
		foreach( $allPlayer as $key => $player_info  )
		{
			$str = str_replace( $player_info->name ,"<a style='text-decoration:underline;color:red;' href='/playerdetail/".$player_info->player_id."'>".$player_info->name."</a>",$str);
		}
		
		
		// 获取积分榜里的球队
		// $scorerank = DB::table('scorerank')
					// -> get();
		// 存放 所有球队的名字
		// $footName = array();
		// foreach( $scorerank as $key => $score )
		// {
			// 球队名字
			// if( !in_array($score -> name_zh,$footName) )
			// {
				// array_push($footName,$score -> name_zh);
			// }
		// }
		// 获取 全部赛程直播
		// $live_list = DB::table('saicheng')
				// -> select( 'id','c4T1','c4T2' )
				// -> where( 'c1','=','未开赛' )
				// 大于 此刻
				// -> where( 'c2','>',date('Y-m-d H:i:s') )
				// 先按 c2
				// -> orderBy('c2')
				// 先按 c3
				// -> orderBy('c3','desc')
				// -> get();
		// foreach( $live_list as $key=> $live_info )
		// {
			// 不存在的球队 先剔除
			// if( !in_array($live_info->c4T1,$footName) || !in_array($live_info->c4T2,$footName)  )
			// {
				// continue;
			// }else
			// {
			
				// $str = str_replace( $live_info->c4T1."vs".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
				// $str = str_replace( $live_info->c4T1."VS".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
				// $str = str_replace( $live_info->c4T1."与".$live_info->c4T2,"<a style='text-decoration:underline;color:red;' href='/live_preview/".$live_info->id."'>".$live_info->c4T1."vs".$live_info->c4T2."</a>",$str);
			// }
		// }
		
		// 获取 全部 球队 
		$allTeam = DB::table('team_info')
			-> select('name','team_id')
			-> get();
		
		foreach( $allTeam as $key => $team_info  )
		{
			$str = str_replace( $team_info->name ,"<a style='text-decoration:underline;color:red;' href='/teamdetail/".$team_info->team_id."'>".$team_info->name."</a>",$str);
		}
		
		// 改变alt
		$str = str_replace("<img","<img alt='".$article->title."' title='".$article->title."'",$str);
		$article->content = $str ;
		
		
		
		// 获取 评论 
		$comments = DB::table('comments as c')
				-> select( 'u.name','c.create_at','c.content','c.id','c.user_id','c.good',DB::raw("replace(u.pic_url,'/images','".config('app.imgPath')."/images' ) as pic_url "  ) )
				-> leftJoin( 'user as u','u.id','=','c.user_id' )
				-> where( 'c.record_id','=',$article_id )
				// 文章 类型
				-> where( 'c.type','=',2 )
				// 评论 时间
				-> orderBy('c.create_at','desc')
				-> paginate(5);
		$comments_total = DB::table('comments as c')
			-> where( 'record_id','=',$article_id )	
			// 文章 类型
			-> where( 'c.type','=',2 )					
			-> count();
		// 获取 评论 回复 
		$comments_reply = array();
		foreach( $comments as $key => $comment_info )
		{
			// 评论id
			$comment_id = $comment_info->id;
			$replys = DB::table('reply as r')
						-> select('r.*','u.name as username','uu.name as replyname',DB::raw("replace(uu.pic_url,'/images','".config('app.imgPath')."/images' ) as uupic_url ") )
						-> leftJoin('user as u','u.id','=','r.user_id')
						-> leftJoin('user as uu','uu.id','=','r.reply_user_id')
						-> where( 'r.comment_id','=',$comment_id )	
						// 回复 时间
						-> orderBy('r.create_at')
						-> get();
			$reply = array();
			foreach( $replys as $k => $reply_info )
			{
				
				$reply[$k]['id'] = $reply_info->id;
				$reply[$k]['comment_id'] = $reply_info->comment_id;
				$reply[$k]['good'] = $reply_info->good;
				$reply[$k]['user_id'] = $reply_info->user_id;
				$reply[$k]['content'] = $reply_info->content;
				$reply[$k]['reply_user_id'] = $reply_info->reply_user_id;
				$reply[$k]['create_at'] = $reply_info->create_at;
				$reply[$k]['username'] = $reply_info->username;
				$reply[$k]['replyname'] = $reply_info->replyname;
				$reply[$k]['uupic_url'] = $reply_info->uupic_url;
			}
			$comments_reply[$key] = $reply;
		}
		
		// 获取 推荐专区
		$recommend = $this -> getRecommend();

        $webConfig = DB::table('webconfig')
            -> select('webName')
            -> where('id',1)
            -> first();


        // 详情 模板
		return view( 'article.detail',['webConfig'=>$webConfig,'article'=>$article,'recommend'=>$recommend,'comments'=>$comments,'comments_total'=>$comments_total,'comments_reply'=>$comments_reply ] );
		
		
	}
	
	
	// 删除 文章
	public function delArticle( Request $request )
	{
		// 包含 文章 id
		$data = $request -> except('_token');
		
		$pics = DB::table('article_pic')
				-> where( 'article_id','=',$data['article_id'] )
				-> get();
		foreach( $pics as $key => $pic_info )
		{
			// 线上
			$file = "../../image".$pic_info -> pic_url;
			// 删除 文件
			if( file_exists($file) )
			{
				unlink($file);
			}
		}
		
		// 1.从表
		DB::table('article_pic')
			-> where( 'article_id','=',$data['article_id'] )
			-> delete();	
		
		// 2.主表
		$res = DB::table('article')
				-> where( 'id','=',$data['article_id'] )
				-> delete();
		if( !$res )
		{
			$this -> show_msg('删除失败');
		}
		$this -> show_msg('删除成功');
	
	}
	
	
	
	
}
